import Layout from '../core/Layout'
import { Form, Input, Upload,Button, Select, message } from 'antd'
import { UploadOutlined } from '@ant-design/icons'
import { useState} from 'react'
import axios from 'axios'
import {API} from '../../config'
import { isAuth } from '../../helpers/auth'
import { useHistory } from 'react-router-dom'
import useGetCategoriers from '../../helpers/getCategory'

function AddProduct() {
  const [file,setFile] = useState()
  const categories = useGetCategoriers()
  const {user,token} = isAuth()
  const [form ] =Form.useForm()
  const props = {
    beforeUpload(file){
      setFile(file)
      return false
    }
  }
  const history = useHistory()

  const OnFinish =value =>{
    const formData = new FormData()
    for(let attr in value){
      formData.append(attr,value[attr])
    }
    formData.append("photo",file)
    axios.post(`${API}/product/create/${user._id}`,formData,{
      headers:{
        Authorization:`Bearer ${token}`
      }
    }).then(()=>{
      message.success("商品添加成功")
      form.resetFields()
      history.push('/admin/dashboard')
    }).catch(err=>{
      console.log(err)
    })
  }
  
  return (
    <Layout title="添加商品" subTitle="快加入你的商品吧">
      <Form form={form} initialValues={{category:"-1"}} onFinish={OnFinish}>
        <Form.Item label="上传封面">
          <Upload {...props}>
            <Button icon={<UploadOutlined />}>上传图书封面</Button>
          </Upload>
        </Form.Item>
        <Form.Item label="商品名称" name="name">
          <Input />
        </Form.Item>
        <Form.Item label="商品描述" name="description">
          <Input />
        </Form.Item>
        <Form.Item label="商品价格" name="price">
          <Input />
        </Form.Item>
        <Form.Item label="商品分类" name="category">
          <Select>
            <Select.Option value="-1">请选择分类</Select.Option>
            {
              categories.map(({name,_id}) =>(
                <Select.Option key={_id} value={_id}>{name}</Select.Option>
              ))
            }
          </Select>
        </Form.Item>
        <Form.Item label="商品数量" name="quantity">
          <Input />
        </Form.Item>
        <Form.Item label="是否需要运输" name="shipping">
          <Select>
            <Select.Option value="1">是</Select.Option>
            <Select.Option value="0">否</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">添加商品</Button>
        </Form.Item>
      </Form>
    </Layout>
  )
}

export default AddProduct
